<?php
namespace App\Controller\App;

use App\Query\OrderQuery;
use App\Query\UserAddressQuery;
use App\Repository\ProductRepository;
use App\Repository\OrderRepository;

class OrderController extends Controller
{
    // 创建订单
    public function index($id)
    {
        $user = $this->auth();
        
        // 获取商品
        if(!$product = ProductRepository::find($id))
        {
            $this->error('error');
        }
        
        // 库存
        if(!$count = $product->hasCount($this->input('count')))
        {
            $this->error('product_count');
        }
        
        // 限制时间数量
        if($dayCount = $product->isDay())
        {
            // 查询订单
            $dayCount = OrderQuery::dayCount(OrderQuery::user($this->auth()), $product->isDay());
            
            if($product->isDayCount($dayCount + $count))
            {
                $this->error('product_day_count');
            }
        }
        
        // 算出价格
        $money = $product->makeMoney($count);
        
        // 收货地址
        if(!$address = UserAddressQuery::user($user)->first())
        {
            $this->error('address');
        }
        
        // 扣掉余额
        if(!$user->moneyMake($money, '购买【' . $product->name . '】商品'))
        {
            $this->error('money');
        }
        
        // 扣除库存
        $product->makeCount($count);

        // 创建订单
        OrderRepository::make()->create($user, $product, [
            'name'    => $address->name,
            'phone'   => $address->phone,
            'data'    => $address->data,
            'address' => $address->address,
            'count'   => $count,
            'money'   => $money
        ]);
        
        $this->message('ok');
    }

    // 我的订单
    public function user()
    {
        return OrderQuery::query(
            OrderQuery::user($this->auth()),
            $this->inputs('status')
        )->paginate(10)->toArray();
    }
}
